<template>
  <div class="peisong_model"><!--  v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}"-->
    <el-dialog title="配送" class="noselect"
               :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
      <div style="margin: 20px;"></div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label=" ">
                <div class="el-from-item_title">卡类型</div>
                <div class="el-from-item_content text-left" style="margin-left:80px">
                    <el-radio >{{modelForm.cardTypeName}}</el-radio>
                </div>
        </el-form-item>
        <el-form-item label=" " prop="" :rules="[ { required: true, message: '请选择所属区域', trigger: 'change' }]" style="position:relative;">
          <div class="text-left">所选卡类型适用门店：
          <!--  <span v-if="branches && branches.length>0" v-for="item in branches" class="m-l-15">
              <el-tag type="success" class="text-left">{{item.name}}</el-tag>
            </span>-->
          </div>
          <div class="shiyong_branch">
            <span v-if="branches && branches.length>0" v-for="item in branches" class="m-l-15">
              <el-tag type="success" class="text-left">{{item.name}}</el-tag>
            </span>

          </div>

          <div class="el-input el-input-group el-input-group--prepend el-input--medium" >
            <div class="el-input-group__prepend" tabindex="-1">配送门店</div>
            <el-input placeholder="请选择" v-model="districtName" auto-complete="off" :maxlength="5" size="medium" >
            <el-button slot="append" icon="el-icon-caret-bottom" @click="goChose()"></el-button>
            </el-input>
          </div>
          <!--<div style="font-size: 13px;color:red;text-align: left" v-if="!hasBranch">单店空卡数量限制在5000以内【{{districtName}}】已存在空卡 【{{cardNum.count}}】,还可下发 【{{cardNum.useCount}}】</div>-->
          <!--style="position: fixed;z-index:9branch_tree99999;background-color: #fff;width:100%;max-height: 30vh;top:80px;overflow-y: auto; height: 200px;"-->
          <div  v-if="isDistricts" class="branch_tree" >
            <div style="text-align:left">
              <el-tree
                id="myPanel"
                class="branch_tree_container"
                :data="treeData"
                show-checkbox
                node-key="value"
                :check-strictly="true"
                ref="tree"
                :default-checked-keys="checkedKey"
                default-expand-all
                @check-change="checkChange" @node-click="nodeClick">
              </el-tree>
            </div>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="no" :rules="[]">
          <el-row>
            <el-col :span="24">
              <el-input placeholder="" v-model.number="modelForm.peiSongCount"  auto-complete="off" :maxlength="15" size="medium" :disabled="hasBranch" @blur="isNum(modelForm,'peiSongCount');getRange()">
                <template slot="prepend">
                  <el-tooltip placement="top" content="配送数量">
                    <el-button tabIndex="-1">配送数量</el-button>
                  </el-tooltip>
                </template>
              </el-input>
            </el-col>

            <!--<el-col :span="14" class="text-left" ><span style="padding-left:10px;">本批次可选卡数量为:{{modelForm.count-modelForm.deliverCount}}<span v-if="!hasBranch">,本门店最多可以配送:{{cardNum.useCount}} 个</span> </span></el-col>-->
          </el-row>
          <div class="text-left">
            <span style="padding-left:10px;">本批次可选卡数量为:{{modelForm.count-modelForm.deliverCount}}<span v-if="!hasBranch">,本门店最多可以配送:{{cardNum.useCount}} 个</span> </span>
            <br /><span class="p-l-10" style="font-size: 13px;color:red;" v-if="rangeShow">待下发的卡号范围：{{range.startNo}}-{{range.endNo}}</span>
            <span v-else>&nbsp;</span>
          </div>
          <!--<div class="text-left" v-if="rangeShow" style="font-size: 13px;color:red;">待下发的卡号范围：{{range.startNo}}-{{range.endNo}}</div>-->
    <!--<div class="text-left" style="font-size: 13px;color:red;">已配送的会员卡不能进行删除操作！</div>-->
        </el-form-item>
        <!-- <el-form-item label=" " prop="parentId" :rules="[{ required: true, message: '请选择所属业态', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium" >
            <div class="el-input-group__prepend" tabindex="-1">所属业态</div>
            <el-cascader :disabled="isUpdate" placeholder="请选择" class="el-cascader-margin w-100p"  size="medium"
                         :options="treeData"
                         :show-all-levels="false" v-model="downCategeryId"
                         change-on-select>
            </el-cascader>
          </div>
        </el-form-item> -->
      </el-form>
      <div style="height:100px;"></div>
      <div class="foot-bar-button">
        <el-button :disabled="canSave" type="primary" size="medium" @click="submitForm('modelForm')">
          <span v-if="canSave"><i class="el-icon-loading"></i>提交中</span>
          <span v-else>提交</span>
        </el-button>
        <!--<el-button type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>-->
        <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
//注意路径
export default {
  props: ["isShow", "id"], //参数
  data() {
    return {
      canSave:false,
      modelForm: {
        type:'',
      },
      hasBranch:true,
      showDialog: false,
      activityId: "",
      isSave: true,
      downCategeryId: [],
      isUpdate: false,
      districtName:"",
      districtId:"",
      isDistricts:false,
      treeData:[],
      checkedKey:[],

      selectDistrict:[],
      record:{},
      editCheckId:"",
      cardNum:{},
      range:{},
      rangeShow:false,
      branches:[]
    };
  },
  watch: {
    isShow: function(newValue, oldValue) {
      this.showDialog = newValue;
      this.districtName = "";
      this.rangeShow=false;
      this.hasBranch=true;
      this.canSave=false;
      if (newValue) {
        if (this.id != "") {
          this.activityId = this.id;
          this.isSave = false;
          this.isUpdate = true;

          this.$axios
            .get("members/batchCardRecords/delivery?id=" + this.activityId)
            .then(data => {
              data.content.record.peiSongCount=0;
              this.modelForm = data.content.record;
              var dataValue = data.content;
              var tree = dataValue.districts;
              this.newLabel(tree);
              this.treeData = tree;
              this.branches = dataValue.branches;

            });
        }
      }
    }
  },
  mounted(){
    let _this=this;
    document.addEventListener("click",function(event){
      var sp = document.getElementById("myPanel");
      if(sp){
        if(!sp.contains(event.target)){            //这句是说如果我们点击到了id为myPanel以外的区域
          _this.isDistricts=false;
        }
      }
    })
  },
  created() {
    window.this = this;
  },
  methods: {
    getRange(){
      var count = this.modelForm.count-this.modelForm.deliverCount;
      if(this.modelForm.peiSongCount*1>count*1){
        this.$message.error("配送数量不能大于可选卡的数量");
        this.modelForm.peiSongCount=0;
        return false;
      }
      if(this.modelForm.peiSongCount*1>this.cardNum.useCount*1){
        this.$message.error("配送数量不能大于门店最多配送数量");
        this.modelForm.peiSongCount=0;
        return false;
      }
      if(this.modelForm.peiSongCount*1<=0){
        return false;
      }
      this.$axios
        .get("members/batchCardRecords/getNoRange",{batchId:this.modelForm.id,count:this.modelForm.peiSongCount})
        .then(data => {
          if (data.status == 200) {
              this.range=data.content;
              this.rangeShow=true;
          } else {
            this.$message.error(data.message);
          }
        });
    },
    goChose(){
       this.isDistricts=!this.isDistricts;
    },
    checkChange(item,node,self){
      this.checkedKey=[];
      if(node==true && item.iBranch){    //点击未选中复选框
        this.editCheckId=item.value;
        this.$refs.tree.setCheckedKeys([item.value]);
        this.districtName=item.name;
        this.districtId=item.id;
      }else{
        if(this.editCheckId==item.value && item.iBranch){   //点击已选中复选框，保证选中一个
          this.$refs.tree.setCheckedKeys([item.value]);
          this.districtName=item.name;

        }
      }


      this.checkedKey.push(this.districtId+"_b")
      this.hasBranch=false;

      this.$axios.get("members/batchCardRecords/getUsableCard?branchId="+this.districtId).then(res=>{
        if(res.success){
          this.cardNum=res.content;

          console.log(this.cardNum);
        }
      },res=>{})

      this.isDistricts=!this.isDistricts;
    },
    nodeClick(item,node,self){

      if( item.iBranch){
        this.editCheckId=item.value;
        this.$refs.tree.setCheckedKeys([item.value]);
      }
    },
    getCurrent(){
      // this.selectDistrict=[];
      // this.districtId=[];
      // var getCheck=this.$refs.tree.getCheckedNodes();
      // for(let i=0;i<getCheck.length;i++){
      //   if(getCheck[i].iBranch==true){
      //     this.selectDistrict={name:getCheck[i].name,id:getCheck[i].id};
      //     this.districtId=getCheck[i].id;
      //   }
      // }
      // this.districtName="";
      // if(this.selectDistrict.length>0){
      //     this.districtName =this.selectDistrict[j].name;
      //
      // }
    },
    newLabel(newList) {
      if (newList) {
        for (var i = 0; i < newList.length; i++) {
          console.log(newList[i].iBranch);
          if(newList[i].iBranch){
            newList[i].value = newList[i].id + "_b";
          }else {
            newList[i].value = newList[i].id + "";
          }
          newList[i].label = newList[i].name;
          if (!newList[i].children || newList[i].children.length == 0) {
            newList[i].children = null;
          } else {
            for (var s = 0; s < newList[i].children.length; s++) {
              if(newList[i].iBranch){
                newList[i].children[s].value = newList[i].children[s].id + "_b";
              }else {
                newList[i].children[s].value = newList[i].children[s].id + "";
              }
              newList[i].children[s].label = newList[i].children[s].name;
              this.newLabel(newList[i].children[s].children);
            }
          }
        }
      }
    },
    goBack() {
      this.router.go(-1);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var data={};
          if(this.districtId==''){
            this.$message.error("请选择配送门店")
            return false;
          }
          // if(this.range.endNo || this.range.startNo || (this.modelForm.peiSongCount*1<=0)){
          //   this.$message.error("请填写卡配送数量")
          //   return false;
          // }

          data.batch=this.modelForm.id;
          data.cardTypeId=this.modelForm.cardTypeId;
          data.branchId=this.districtId;
          data.branchName=this.districtName;
          data.startNo=this.range.startNo;
          data.endNo=this.range.endNo;
          data.count=this.modelForm.peiSongCount;
          // if(this.modelForm.peiSongCount)
          if(this.canSave){
            return;
          }
          this.canSave=true;
            this.$axios
              .post("members/deliveryRecords/create",data)
              .then(data => {
                if (data.status == 200) {
                  this.canSave=false;
                  this.$message({
                    message: data.message,
                    type: "success"
                  });
                  this.$emit("addSuccess");
                } else {
                  this.canSave=false;
                  this.$message.error(data.message);
                }
              });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$emit("close");
      this.showDialog = false;
    },
    handleClose() {
      console.log("dddddddddddd");
      this.$emit("close");
      this.showDialog = false;
//      done();
    },
    isNum(item, key) {
      var r = /^\+?[1-9][0-9]*$/;
      if (!r.test(item[key])) {
        item[key] = "0.00";
      } else {
        item[key] = item[key];
      }
    },
    isDouble(item, key) {
      var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
      if (!isNum.test(item[key])) {
        item[key] = "0.00";
      } else {
        item[key] = item[key];
      }
    }
  }
};
</script>
<style scoped>
.el-from-item_title {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #48576a;
  line-height: 1;
  padding: 11px 12px 11px 0;
  box-sizing: border-box;
}
.el-from-item_content {
  line-height: 36px;
  position: relative;
  font-size: 15px;
}

  .shiyong_branch{
    border: 1px solid #dfe6ec;
    height: 79px;
    text-align: left;
    overflow: auto;
   padding-left: 10px;
    margin-bottom: 15px;
}

</style>
